'''
Created on 29/03/2011

@author: Eran_Z

Searching
'''

from math import log
import random
import sys
import google_m

def __search(searchStr):
    """Searches given search string on the web.
    Returns number of hits."""
    temp = int(sys.maxint*random.random())
    print searchStr + " : " + str(temp)
    return temp
    #return google_m.showsome(searchStr)
    
def searchSingle(term):
    """Returns number of hits for given term."""
    try:
        index = __history.index(term)
    except ValueError:
        #isn't in the list
        hits = __search("\"" + term + "\"")
        __history.append(term)
        __history.append(hits)
        return hits
    else:
        return __history[index + 1]

def searchTogether(term1, term2):
    """Returns number of hits for 2 given terms together."""
    try:
        index = __history.index((term1, term2))
    except ValueError:
        #isn't in the list
        hits = __search("\"" + term1 + "\" \"" + term2 + "\"")
        __history.append((term1, term2))
        __history.append(hits)
        __history.append((term2, term1))
        __history.append(hits)
        return hits
    else:
        return __history[index + 1]

def searchExclusion(term, Ex):
    """Returns number of hits for given term,
    excluding pages containing terms from the given exclusion group."""
    searchStr = "\"" + term + "\""
    for str in Ex:
        searchStr += " -\"" + str + "\""
    return __search(searchStr)

def NGD(x,y):
    logx = log(searchSingle(x))
    logy = log(searchSingle(y))
    logxy = log(searchTogether(x,y))
    logN = log(google_m.N)
    return (max(logx, logy) - logxy) / (logN - min(logx, logy))
    

#a search history, currently saves only 'single' and 'together' searches.
#acts as a sort of cache, eliminating the need of repeated sessions.
__history = []
